Java syntax
part 18/36 Β· 136.0 KB total
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Reference types
Reference types include class types, interface types, and array types.
When the constructor is called, an object is created on the heap and a
reference is assigned to the variable. When a variable of an object gets
out of scope, the reference is broken and when there are no references
left, the object gets marked as garbage. The garbage collector then
collects and destroys it some time afterwards.
A reference variable is null when it does not reference any object.
Arrays
Arrays in Java are created at runtime, just like class instances. Array
length is defined at creation and cannot be changed.
int[] numbers = new int[5];
numbers[0] = 2;
numbers[1] = 5;
int x = numbers[0];
Initializers
// Long syntax
int[] numbers = new int[] {20, 1, 42, 15, 34};
// Short syntax
int[] numbers2 = {20, 1, 42, 15, 34};
Multi-dimensional arrays
In Java, multi-dimensional arrays are represented as arrays of arrays.
Technically, they are represented by arrays of references to other
arrays.
int[][] numbers = new int[3][3];
numbers[1][2] = 2;
int[][] numbers2 = {{2, 3, 2}, {1, 2, 6}, {2, 4, 5}};
Due to the nature of the multi-dimensional arrays, sub-arrays can vary
in length, so multi-dimensional arrays are not bound to be rectangular
unlike C:
int[][] numbers = new int[2][]; //Initialization of the first dimension
only
numbers[0] = new int[3];
numbers[1] = new int[2];
Classes
Classes are fundamentals of an object-oriented language such as Java.
They contain members that store and manipulate data. Classes are divided
into top-level and nested. Nested classes are classes placed inside
another class that may access the private members of the enclosing
class. Nested classes include member classes (which may be defined with
the static modifier for simple nesting or without it for inner classes),
local classes and anonymous classes.
Declaration
| Top-level class | class Foo { // Class members } |
|---|---|
| Inner class | class Foo { // Top-level class class Ba⦠|
| Nested class | class Foo { // Top-level class static c⦠|
| Local class | class Foo { void bar () { class Foobar⦠|
| Anonymous class | class Foo { void bar () { new Object ()β¦ |
Instantiation
Non-static members of a class define the types of the instance variables
and methods, which are related to the objects created from that class.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ